package com.examples.gateway.util;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName ThreadPoolUtil
 * @Description: TODO 线程池工具类
 * @Author Dai YaLu
 * @date: 2024/4/1
 * @Version: 1.0
 */
public class ThreadPoolUtil {

    /**
     * 核心线程数，会一直存活，即使没有任务，线程池也会维护线程的最少数量
     */
    private static final int SIZE_CORE_POOL = 10;

    /**
     * 线程池维护线程的最大数量
     */
    private static final int SIZE_MAX_POOL = 50;

    /**
     * 线程池维护线程所允许的空闲时间 ms
     */
    private static final long ALIVE_TIME = 2000;

    /**
     * 线程缓冲队列，超过这个数量的线程将会阻塞
     */
    private static final BlockingQueue<Runnable> BQUEUE = new ArrayBlockingQueue<>(200);

    /**
     * 注意最后的参数是： RejectedExecutionHandler 是任务拒绝策略
     */
    private static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(SIZE_CORE_POOL, SIZE_MAX_POOL, ALIVE_TIME, TimeUnit.MILLISECONDS, BQUEUE,
            new ThreadPoolExecutor.CallerRunsPolicy());

    static {
        /*
         * 启动核心线程
         */
        POOL.prestartAllCoreThreads();
    }

    public static ThreadPoolExecutor getPool() {
        return POOL;
    }
}
